<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// | 该文件的开源协议以所在项目的LICENSE文件为准，请遵守开源协议要求
// +----------------------------------------------------------------------
// | 获取文章上一篇
// +----------------------------------------------------------------------
namespace app\cms\tags;

use app\cms\helper\cache;
use app\cms\model\ArchiveModel;
use app\cms\model\CategoryModel;
use app\cms\model\TagsModel;
use Inphp\Core\Context;
use Inphp\Core\Db\PDO\Query;

class prevNext extends aTag
{
    public static function process(array $params): array
    {
        $id = $params["id"] ?? 0;
        $id = is_numeric($id) && $id > 0 ? ceil($id) : 0;
        if ($id <= 0) {
            return [];
        }
        $categoryId = $params["categoryId"] ?? 0;
        $categoryId = is_numeric($categoryId) && $categoryId > 0 ? ceil($categoryId) : 0;
        //站点识别
        $site = Context::get("CMS_SITE");
        $siteId = $site ? $site["id"] : 0;
        //
        $prev = self::get($id, $categoryId, $siteId, false);
        $next = self::get($id, $categoryId, $siteId, true);
        if (empty($prev) && empty($next)) {
            return [];
        }
        $data = [
            //因为使用遍历，所以返回该数据
            [ "prev" => $prev, "next" => $next ]
        ];
        return isset($params["assign"]) ? $data[0] : $data;
    }

    /**
     * 获取
     * @param int $id
     * @param int $categoryId
     * @param int $siteId
     * @param bool $next
     * @return array
     */
    public static function get(int $id, int $categoryId, int $siteId, bool $next = true): array
    {
        //优先从缓存中获取
        $params = func_get_args();
        $cache = cache::get($params, $next ? "archive/next" : "archive/prev");
        if (!empty($cache)) {
            return $cache;
        }
        //从数据库查询
        $db = ArchiveModel::emptyQuery("a")
            ->leftJoin(CategoryModel::tableName()." c", "a.categoryId=c.id")
            ->where("a.id", $next ? ">" : "<", $id);
        if ($categoryId > 0) {
            $db->where("a.categoryId", $categoryId);
        }
        $item = $db->where(function (Query $query) use ($siteId) {
                $query->whereNumberInSet([$siteId, 0], "a.siteId")
                    ->orWhereEmpty("a.siteId");
            })->where("a.state", 1)->where("a.recycle", 0)->select([
            "a.id, a.uid, a.siteId, a.categoryId, a.index, a.title, a.keyword, a.description, a.pictures, a.url, a.time, a.updateTime, a.tags, a.good, a.bad, a.top, a.clicks, a.recycle, a.state, a.template",
            //分类
            "c.name as categoryName"
        ])->orderBy("a.id", $next ? "asc" : "desc")->first();
        if (empty($item)) {
            return [];
        }
        $item["pictures"] = attachmentsUrl($item["pictures"]);
        $item["preview"] = !empty($item["pictures"]) ? $item["pictures"][0] : null;
        //
        $item["userNickname"] = !empty($item["userNickname"]) ? decodeNickname($item["userNickname"]) : null;
        $item["userFace"] = isset($item["userFace"]) ? attachmentUrl($item["userFace"]) : null;
        //生成链接，需要匹配完成的域名
        $item["url"] = makeCMSUrl($item);
        $item["title"] = filterIllegalString($item["title"]);
        $item["keyword"] = filterIllegalString($item["keyword"]);
        $item["description"] = filterIllegalString($item["description"]);
        //查询标签
        $item["tagList"] = !empty($item["tags"]) ? TagsModel::getList($item["tags"]) : [];
        $item["tags"] = [];
        foreach ($item["tagList"] as $tag) {
            $item["tags"][] = $tag["tag"];
        }
        $item["tags"] = join(",", $item["tags"]);
        $item["datetime"] = strtotime($item["time"]);
        //保存至缓存
        cache::set($params, $item, $next ? "archive/next" : "archive/prev");
        return $item;
    }
}